<?php
namespace app\api\controller\customer;


use app\api\controller\Api;
use app\common\customer\model\UploadFile;
use app\common\third\Excel;

class Upload extends Api
{
    public function doUpload()
    {
        $post = $this->request->post();
        if (empty($post['source_id'])) return error([], '请选择渠道');
        if (empty($post['file_path'])) return error([], '请上传文件');

        $env = getenv("SERVER_ENV");
        $config = config('filesystem.disks');
        if ($env == 'test') {
            $root = $saveName = $config['public']['root'];
        } else {
            $root = $saveName = $config['image']['root'];
        }

        $user = $this->request->user;
        $data = [];
        $data['user_id'] = $user['id'];
        $data['source_id'] = $post['source_id'];
        $data['file_path'] = $post['file_path'];
        $data['file_name'] = $post['file_name'];
        $data['hash_code'] = $post['hash_code'];
        $model = new UploadFile();
        try {
            $rs = $model->save($data);
        } catch(\Exception $e) {
            return error([], $e->getMessage());
        }

        // 读取excel文件内容
        $filePath = $root . '/' . $post['file_path'];
        $rows = Excel::read($filePath);
        if (empty($rows)) return error([], '文件内容为空');


        foreach ($rows as $row) {
            // 读取当前行的数据
            $data = [];
            $data['upload_file_id'] = $model->id;
            $data['source_id'] = $post['source_id'];
            $data['fullname'] = $row[0];
            $contact = $row[1];
            // 判断是否是手机号
            if (preg_match("/^1[3456789]\d{9}$/", $contact)) {
                $data['contact_type'] = 1;
            } else {
                $data['contact_type'] = 2;
            }
            $data['contact'] = $contact;
            $data['store'] = $row[2];
            $data['store_id'] = $row[2];
            $data['event_date'] = $row[3];
            $data['budget'] = $row[3];
        }

        $data = [];
        $data['upload_file_id'] = $model->id;
        

    }
}